/**
 * 计划管理 -- 计划审核
 * @author xiaoxujs
 */

import { useCallback, useEffect, useState } from "react";
import SearchModule from "./components/SearchModule";
import { PlanReviewBox } from "./style";
import { ISelectList, TablePaginationPosition } from "../../../type/antd";
import { IPlanPlanApprovalPage, IPlanPlanApprovalPageParams, IPlanPlanPageSearchForm } from "../../../type/planManagement";
import dayjs from "dayjs";
import { getPlanGoodsNames, getPlanTransportNames, postPlanPlanApprovalPage } from "../api";
import { IFenye, INoFenye } from "../../../type/commit";
import { Button, ConfigProvider, message, Table, TableProps, Tabs, TabsProps, Tooltip } from "antd";
import { useWindowFontSize } from "../../../assets/fun/Antd/configprovider";
import { handleGetDictionaryItemData } from "../../../assets/fun/DictionaryItem";
import { dictionaryStyle } from "../../../assets/style/DictionaryItem";
import ToExamineModule from './components/ToExamineModule'

const PlanReview = () => {
    const contentValue: TablePaginationPosition = "bottomCenter"; //位置

    const [goodsList, setGoodsList] = useState<ISelectList[]>([]); //  货品下拉数据
    const [transportNameList, setTransportNameList] = useState<ISelectList[]>([]); //物流单位数据
    const [approvalState, setApprovalState] = useState('1');
    const [searchValue, setSearchValue] = useState<IPlanPlanPageSearchForm>(); //设置

    const [listData, setListData] = useState<IPlanPlanApprovalPage[]>([]);
    const [paging, setPaging] = useState({
        currentPage: 1,
        pageSize: 3,
    });
    const [total, setTotal] = useState(0);
    const [tableLoading, setTableLoading] = useState(false); //tableLoading
    const [clickId, setClickId] = useState<string>(); //点击ID
    const [toExamineShow, setToExamineShow] = useState(false); //审批计划 show

    const zhidianFun = useCallback(async () => {
        const goodsValue = await getPlanGoodsNames() as INoFenye<string>;
        if (goodsValue.code === 20000) {
            let arrGoods: ISelectList[] = []
            goodsValue.data.forEach(element => {
                arrGoods.push({
                    value: element,
                    label: element
                })
            });
            setGoodsList([...arrGoods]);
        } else {
            message.error(goodsValue.msg);
        }
        const { code, msg, data } = await getPlanTransportNames() as INoFenye<string>;
        if (code === 20000) {
            let arr: ISelectList[] = []
            data.forEach(element => {
                arr.push({
                    value: element,
                    label: element
                })
            });
            setTransportNameList([...arr]);
        } else {
            message.error(msg);
        }
    }, []);

    useEffect(() => {
        zhidianFun();
    }, [zhidianFun])
    const listFun = useCallback(async (params: IPlanPlanApprovalPageParams) => {
        setTableLoading(true);
        const { code, msg, data } = (await postPlanPlanApprovalPage(
            params
        )) as IFenye<IPlanPlanApprovalPage>;
        if (code === 20000) {
            setListData(data.records);
            setPaging({
                currentPage: params.currentPage,
                pageSize: params.pageSize,
            })
            setTotal(data.total);
            setTableLoading(false);
            setApprovalState(params.approvalState);
        } else {
            message.error(msg);
        }
    }, []);
    useEffect(() => {
        const params = {
            approvalState: '1',
            currentPage: 1,
            pageSize: 10
        }
        listFun(params);
    }, [listFun])

    // 检索
    const handleSearchCallback = (value?: IPlanPlanPageSearchForm) => {
        if (value) {
            const params: IPlanPlanApprovalPageParams = {
                approvalState,
                currentPage: 1,
                pageSize: 10,
                goodsName: value.goodsName,
                transportName: value.transportName,
                startDate: value.date ? dayjs(value.date[0]).format('YYYY-MM-DD') : undefined,
                stopDate: value.date ? dayjs(value.date[1]).format('YYYY-MM-DD') : undefined,
            }
            listFun(params);

        } else {
            const params = {
                approvalState: approvalState,
                currentPage: 1,
                pageSize: 10
            }
            listFun(params);
        }
        setSearchValue(value);
    }
    //  审批计划 
    const handleToExamineCallback = () => {
        setToExamineShow(false);
        setClickId(undefined);
        const params = {
            approvalState: approvalState,
            currentPage: paging.currentPage,
            pageSize: paging.pageSize,
            goodsName: searchValue && searchValue.goodsName,
            transportName: searchValue && searchValue.transportName,
            startDate: searchValue && searchValue.date ? dayjs(searchValue.date[0]).format('YYYY-MM-DD') : undefined,
            stopDate: searchValue && searchValue.date ? dayjs(searchValue.date[1]).format('YYYY-MM-DD') : undefined,
        }
        listFun(params)
    }
    // 表单切换
    const handleTabsChange = (key: string) => {
        const params = {
            approvalState: key,
            currentPage: 1,
            pageSize: 10,
            goodsName: searchValue && searchValue.goodsName,
            transportName: searchValue && searchValue.transportName,
            startDate: searchValue && searchValue.date ? dayjs(searchValue.date[0]).format('YYYY-MM-DD') : undefined,
            stopDate: searchValue && searchValue.date ? dayjs(searchValue.date[1]).format('YYYY-MM-DD') : undefined,

        }
        listFun(params);

    };
    const pagination = {
        //分页
        position: [contentValue],
        //是否可以改变pagesize//
        showSizeChanger: true,
        //是否可以快速跳转到某页
        showQuickJumper: true,
        //展示一共有多少条数据//
        showTotal: () => `共${total}条`,
        //每页条数
        pageSize: paging.pageSize,
        //当前页数
        current: paging.currentPage,
        //数据总数
        total: total,
        //页码改变的回调，参数是改变后的页码及每页条数
        onChange: (current: number, pageSize: number) => {
            const params = {
                approvalState: approvalState,
                currentPage: current,
                pageSize: pageSize,
                goodsName: searchValue && searchValue.goodsName,
                transportName: searchValue && searchValue.transportName,
                startDate: searchValue && searchValue.date ? dayjs(searchValue.date[0]).format('YYYY-MM-DD') : undefined,
                stopDate: searchValue && searchValue.date ? dayjs(searchValue.date[1]).format('YYYY-MM-DD') : undefined,
            }
            listFun(params)
        },
    };
    const columnsDai: TableProps<IPlanPlanApprovalPage>['columns'] = [
        {
            title: '序号',
            align: 'center',
            render: (_, record, index) => (
                <span>{(paging.currentPage - 1) * paging.pageSize + index + 1}</span>
            ),
        },
        {
            title: '计划编号',
            dataIndex: 'planNo',
            align: 'center',
        },
        {
            title: '计划日期',
            align: 'center',
            render: (_, record) => <span>{record.startDate}~{record.stopDate}</span>
        },

        {
            title: '货品',
            dataIndex: 'goodsName',
            align: 'center',
        },
        {
            title: '物流单位',
            dataIndex: 'transportName',
            align: 'center',
        },
        {
            title: '计划量(吨)',
            dataIndex: 'planQuantity',
            align: 'center',
        },
        {
            title: '剩余量(吨)',
            dataIndex: 'remainingQuantity',
            align: 'center',
        },
        {
            title: '提交人',
            dataIndex: 'createUser',
            align: 'center',
        },
        {
            title: '提交时间',
            dataIndex: 'createTime',
            align: 'center',
        },
        {
            title: ' 操作',
            align: "center",
            render: (_, record) => <Button type="link" onClick={() => {
                setToExamineShow(true);
                setClickId(record.id)
            }}>审批</Button>
        },
    ];
    const columns: TableProps<IPlanPlanApprovalPage>['columns'] = [
        {
            title: '序号',
            align: 'center',
            render: (_, record, index) => (
                <span>{(paging.currentPage - 1) * paging.pageSize + index + 1}</span>
            ),
        },
        {
            title: '计划编号',
            dataIndex: 'planNo',
            align: 'center',
        },
        {
            title: '计划日期',
            align: 'center',
            render: (_, record) => <span>{record.startDate}~{record.stopDate}</span>
        },

        {
            title: '货品',
            dataIndex: 'goodsName',
            align: 'center',
        },
        {
            title: '物流单位',
            dataIndex: 'transportName',
            align: 'center',
        },
        {
            title: '计划量(吨)',
            dataIndex: 'planQuantity',
            align: 'center',
        },
        {
            title: '剩余量(吨)',
            dataIndex: 'remainingQuantity',
            align: 'center',
        },
        {
            title: '提交人',
            dataIndex: 'createUser',
            align: 'center',
        },
        {
            title: '提交时间',
            dataIndex: 'createTime',
            align: 'center',
        },
        {
            title: '审批人',
            dataIndex: 'approvalPersonnel',
            align: 'center',
        },
        {
            title: '审批时间',
            dataIndex: 'approvalTime',
            align: 'center',
        },
        {
            title: '审批结果',
            dataIndex: 'approvalResult',
            align: 'center',
            render: (text, record) => {
                const obj = handleGetDictionaryItemData('SHJG', text);
                if (obj === '无') {
                    return <span>--</span>
                } else {
                    return <Tooltip title={record.approvalReason}>
                        <div style={dictionaryStyle[obj.listClass]}>
                            {obj.cssClass ? <span className='iconfont' style={{ marginRight: '0.5rem' }} dangerouslySetInnerHTML={{ __html: obj.cssClass }}></span> : null}
                            {obj.label}
                        </div>
                    </Tooltip>
                }

            }
        },
    ];
    // 表格
    const JihuaTable = () => {
        return <ConfigProvider theme={{
            components: {
                Table: {
                    headerColor: '#8B9BAC',
                    cellFontSize: useWindowFontSize(14),
                    cellPaddingBlock: 7
                }
            }
        }}>
            <Table<IPlanPlanApprovalPage>
                pagination={pagination}
                rowKey='id'
                columns={approvalState === '1' ? columnsDai : columns}
                dataSource={listData}
                loading={tableLoading}
            />
        </ConfigProvider>
    }
    const items: TabsProps['items'] = [
        {
            key: '1',
            label: '待审核',
            children: JihuaTable(),
        },
        {
            key: '0',
            label: '已审核',
            children: JihuaTable(),
        }
    ];
    return <PlanReviewBox>
        <div className="title">
            计划审核
        </div>
        <SearchModule goodsList={goodsList} transportNameList={transportNameList} handleCallback={handleSearchCallback} />
        <Tabs activeKey={approvalState} items={items} onChange={handleTabsChange} />
        {/* 审批计划 */}
        <ToExamineModule open={toExamineShow} handleCallback={handleToExamineCallback} clickId={clickId} />
    </PlanReviewBox>
}

export default PlanReview;